<?php

$dir = dirname(__FILE__);                //查找当前脚本所在路径
require $dir . "/function.php";           //引入公共函数
require $dir . "/db_config.php";
require $dir . "/db.php";                 //引入数据库连接类
require $dir . "/Pdo.class.php";
require $dir . "/PHPExcel/PHPExcel.php";  //引入phpexcel类
//实例化db类，链接数据库
//$db = new db($phpexcel);
//$data = $db->getResult("select * from tj_gift");
//$data = M($phpexcel)->q("SELECT * FROM tj_gift");
$objPHPExcel = new PHPExcel();          //实例化PHPExcel类，相当于在桌面新建一个excel
for ($i = 1; $i <= 4; $i++) {
    if ($i > 1) {
        $objPHPExcel->createSheet();     //创建内置表
    }
    $objPHPExcel->setActiveSheetIndex($i - 1);    //把新创建的sheet设定为当前活动sheet
    $objSheet = $objPHPExcel->getActiveSheet(); //获取当前活动sheet
    $objSheet->setTitle("分类-" . $i);  //给当前活动sheet取名称
    $data = M($phpexcel)->q("SELECT sub,name,points FROM tj_gift where sub=" . $i); //查询数据
    $objSheet->setCellValue("A1", "分类")->setCellValue("B1", "商品名称")->setCellValue("C1", "积分");
    $j = 2;
    foreach ($data as $key => $val) {
        $objSheet->setCellValue("A" . $j, $val['sub'])->setCellValue("B" . $j, $val['name'])->setCellValue("C" . $j, $val['points']);
        $j++;
    }
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  //生成excel文件
$objWriter->save($dir . "/excel.xls"); //保存文件


/**输出到浏览器**/
browser_export('Excel5', 'browser_excel03.xls');
$objWriter->save('php://output');

function browser_export($type, $filename)
{
        
    if ($type == "Excel5") {
        //告诉浏览器将要输出excel03文件
        header('Content-Type: application/vnd.ms-excel');
    } else {
        //告诉浏览器输出excel07文件
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    }
    //告诉浏览器将要输出文件的名字
    header('Content-Disposition: attachment;filename=' . $filename);
    //禁止缓存
    header('Cache-Control: max-age=0');
}
